package vip.manda.framework.data;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.pool.DruidDataSource;
import vip.manda.framework.core.Configs;

import javax.sql.DataSource;

/**
 * @author hongda.li
 */
public class DataBaseSource {

    private final DataSource dataSource;
    private static final String URL_PREFIX = "jdbc:sqlite:";
    private static class Holder {
        private static final DataBaseSource INSTANCE = new DataBaseSource();
    }

    private DataBaseSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(Configs.getStr(Configs.DataBase.DRIVER));
        dataSource.setTestWhileIdle(true);
        dataSource.setValidationQuery("SELECT 1");
        // init Sqlite
        if (Configs.DataBase.Value.DRIVER.equals(dataSource.getDriverClassName())){
            String path = Configs.getStr(Configs.DataBase.PATH);
            FileUtil.mkdir(path);
            String dataBaseName = Configs.getStr(Configs.DataBase.NAME);
            dataSource.setUrl(URL_PREFIX + path + StrUtil.addSuffixIfNot(dataBaseName, ".db"));
        }else {
            dataSource.setUrl(Configs.getStr(Configs.DataBase.URL));
            dataSource.setUsername(Configs.getStr(Configs.DataBase.USERNAME));
            dataSource.setPassword(Configs.getStr(Configs.DataBase.PASSWORD));
        }
        this.dataSource = dataSource;
    }

    public static DataSource getDataSource() {
        return Holder.INSTANCE.dataSource;
    }
}
